package org.openurp.edu.student.info.web.action

import org.beangle.data.dao.OqlBuilder
import org.beangle.data.dao.EntityDao
import org.beangle.webmvc.api.action.ActionSupport
import org.beangle.webmvc.api.view.View
import org.openurp.edu.student.info.model.User
import org.beangle.webmvc.api.action.ServletSupport
import org.openurp.edu.student.info.model.Student

/**
 * @author King Sun
 */
class LoginAction extends ActionSupport with ServletSupport {

  var entityDao: EntityDao = _

  def index(): String = {
    forward()
  }

  def login(): View = {
    var code = get("username").orNull
    val password = get("password").orNull
    val builder = OqlBuilder.from(classOf[User], "u").where("u.code = :code and u.password = :password", code, password)
    val users = entityDao.search(builder)
    if (users.isEmpty) {
      val sBuilder = OqlBuilder.from[Object](classOf[Student].getName + " student," + classOf[User].getName + " user ")
      sBuilder.where("student.code = user.code").where("student.passportNo = :code and user.password = :password", code, password)
      sBuilder.select("student.code")
      val students = entityDao.search(sBuilder)
      if (students.isEmpty) {

        redirect(to(classOf[LoginAction], "index"), "用户名或者密码错误！")
      } else {
        code = students.head.asInstanceOf[String]
        request.getSession.setAttribute("code", code)
        redirect(to(classOf[HomeAction], "index"), "")
      }

    } else {
      request.getSession.setAttribute("code", code)
      redirect(to(classOf[HomeAction], "index"), "")
    }
  }
  def logout(): View = {

    request.getSession.removeAttribute("code")
    redirect(to(this, "index"), "")
  }
}